from python_nlp.kg.neo4j.config import NEO4J_CONFIG_CBLUE
from neo4j import GraphDatabase
import json
from PyCmpltrtok.common import sep


def query_neo4j(_driver, text, limit=0):
    """
    description: 根据用户对话文本中的可能存在的症状查询图数据库.
    :param text: 用户的输入文本.
    :return: 用户描述的症状对应的疾病列表.
    """
    # 开启一个session操作图数据库
    with _driver.session() as session:
        if limit:
            limit_str = f'LIMIT {limit}'
        else:
            limit_str = ''
        # cypher语句, 匹配句子中存在的所有症状节点,
        # 保存这些节点并逐一通过关系dis_to_sym进行对应病症的查找, 返回找到的疾病名字列表.
        cypher = "MATCH(n:Node) WHERE(n.type = '症状' and %r contains n.name)\
                  MATCH(a:Node{type:'疾病'})-[p:Predicate{name:'临床表现'}]->(n) RETURN a.name %s" % (text, limit_str, )
        # 运行这条cypher语句
        record = session.run(cypher)
        # 从record对象中获得结果列表
        result = list(map(lambda x: x[0], record))
    return result


if '__main__' == __name__:
    
    driver = GraphDatabase.driver(**NEO4J_CONFIG_CBLUE)
    
    xres = query_neo4j(driver, '我最近老咳嗽，还便血。', 0)
    print(xres)
    
    xres = query_neo4j(driver, 'xx', 0)
    print(xres)
